import { ReactElement, useRef, useState, useEffect, RefObject } from 'react'
import { Form, Input, Row, Col, DatePicker, Select, Space, Button, FormInstance } from 'antd'
import moment, { Moment } from 'moment'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import { awaitWrap } from '@src/assets/js/tool'
import { getPersonList } from './ajax'
import { formatEndDate, formatBeginDate } from '@js/tool'
import qs from 'query-string';

const { Item } = Form
const { Option } = Select

export function formatCondition (d: { [k: string]: any }): ConditionSchema[] {
  const r: ConditionSchema[] = []
  if (typeof d.processer === 'string') {
    r.push({ k: 'processer', o: 'like', v: `%${d.processer}%` })
  }
  if (typeof d.accepter === 'string') {
    r.push({ k: 'accepter', o: 'like', v: `%${d.accepter}%` })
  }
  if (typeof d.caseno_desc === 'string') {
    r.push({ k: 'caseno_desc', o: 'like', v: `%${d.caseno_desc}%` })
  }
  if (typeof d.closure_type === 'string') {
    r.push({ k: 'closure_type', o: '=', v: d.closure_type })
  }
  if (typeof d.acceptBegin === 'string' && /^\d+$/.test(d.acceptBegin)) {
    r.push({ k: 'accept_datetime', o: '>=', v: formatBeginDate(d.acceptBegin) })
  }
  if (typeof d.acceptEnd === 'string' && /^\d+$/.test(d.acceptEnd)) {
    r.push({ k: 'accept_datetime', o: '<=', v: formatEndDate(d.acceptEnd) })
  }
  if (typeof d.docketBegin === 'string' && /^\d+$/.test(d.docketBegin)) {
    r.push({ k: 'docket_datetime', o: '>=', v: formatBeginDate(d.docketBegin) })
  }
  if (typeof d.docketEnd === 'string' && /^\d+$/.test(d.docketEnd)) {
    r.push({ k: 'docket_datetime', o: '<=', v: formatEndDate(d.docketEnd) })
  }
  if (typeof d.closureBegin === 'string' && /^\d+$/.test(d.closureBegin)) {
    r.push({ k: 'closure_datetime', o: '>=', v: formatBeginDate(d.closureBegin) })
  }
  if (typeof d.closureEnd === 'string' && /^\d+$/.test(d.closureEnd)) {
    r.push({ k: 'closure_datetime', o: '<=', v: formatEndDate(d.closureEnd) })
  }
  if (typeof d.fileBegin === 'string' && /^\d+$/.test(d.fileBegin)) {
    r.push({ k: 'file_datetime', o: '>=', v: formatBeginDate(d.fileBegin) })
  }
  if (typeof d.fileEnd === 'string' && /^\d+$/.test(d.fileEnd)) {
    r.push({ k: 'file_datetime', o: '<=', v: formatEndDate(d.fileEnd) })
  }
  if (typeof d.applicant === 'string' && d.applicant.length > 0) {
    r.push({ k: 'applicant_name', o: 'like', v: `%${d.applicant}%` })
  }
  if (typeof d.respondent === 'string' && d.respondent.length > 0) {
    r.push({ k: 'respondent_name', o: 'like', v: `%${d.respondent}%` })
  }
  return r
}

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, params: {[k: string]: any}, setParams: (v: {[k: string]: any}) => void): void {
  if (d.acceptDate instanceof Array && d.acceptDate.length > 0) {
    d.acceptBegin = Math.floor((d.acceptDate[0] as Moment).valueOf() / 1000)
    d.acceptEnd = formatEndDate(d.acceptDate[1] as Moment)
    delete d.acceptDate
  } else {
    d.acceptBegin = undefined
    d.acceptEnd = undefined
  }
  if (d.docketDate instanceof Array && d.docketDate.length > 0) {
    d.docketBegin = Math.floor((d.docketDate[0] as Moment).valueOf() / 1000)
    d.docketEnd = formatEndDate(d.docketDate[1] as Moment)
    delete d.docketDate
  } else {
    d.docketBegin = undefined
    d.docketEnd = undefined
  }
  if (d.closureDate instanceof Array && d.closureDate.length > 0) {
    d.closureBegin = Math.floor((d.closureDate[0] as Moment).valueOf() / 1000)
    d.closureEnd = formatEndDate(d.closureDate[1] as Moment)
    delete d.closureDate
  } else {
    d.closureBegin = undefined
    d.closureEnd = undefined
  }
  if (d.fileDate instanceof Array && d.fileDate.length > 0) {
    d.fileBegin = Math.floor((d.fileDate[0] as Moment).valueOf() / 1000)
    d.fileEnd = formatEndDate(d.fileDate[1] as Moment)
    delete d.fileDate
  } else {
    d.fileBegin = undefined
    d.fileEnd = undefined
  }
  const keys = ['caseno_desc', 'processer', 'accepter', 'closure_type', 'applicant', 'respondent']
  keys.forEach(key => {
    if (d[key] === undefined) {
      d[key] = undefined
    }
  })
  d.page = 1
  setParams({
    ...params,
    ...d
  })
}

function initForm (params: {[k: string]:any}, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null) {
    return undefined
  }
  const o = qs.parse(qs.stringify(params))
  const r: { [k: string]: any } = {}
  if (typeof o.caseno_desc === 'string') {
    r.caseno_desc = o.caseno_desc
  }
  if (typeof o.processer === 'string') {
    r.processer = o.processer
  }
  if (typeof o.accepter === 'string') {
    r.accepter = o.accepter
  }
  if (typeof o.acceptBegin === 'string' && /^\d+$/.test(o.acceptBegin) && typeof o.acceptEnd === 'string' && /^\d+$/.test(o.acceptEnd)) {
    r.acceptDate = [moment(parseInt(o.acceptBegin) * 1000), moment(parseInt(o.acceptEnd) * 1000)]
  }
  if (typeof o.docketBegin === 'string' && /^\d+$/.test(o.docketBegin) && typeof o.docketEnd === 'string' && /^\d+$/.test(o.docketEnd)) {
    r.acceptDate = [moment(parseInt(o.docketBegin) * 1000), moment(parseInt(o.docketEnd) * 1000)]
  }
  if (typeof o.closureBegin === 'string' && /^\d+$/.test(o.closureBegin) && typeof o.closureEnd === 'string' && /^\d+$/.test(o.closureEnd)) {
    r.closureDate = [moment(parseInt(o.closureBegin) * 1000), moment(parseInt(o.closureEnd) * 1000)]
  }
  if (typeof o.closure_type === 'string') {
    r.closure_type = o.closure_type
  }

  if (typeof o.fileBegin === 'string' && /^\d+$/.test(o.fileBegin) && typeof o.fileEnd === 'string' && /^\d+$/.test(o.fileEnd)) {
    r.fileDate = [moment(parseInt(o.fileBegin) * 1000), moment(parseInt(o.fileEnd) * 1000)]
  }
  if (typeof o.applicant === 'string') {
    r.applicant = o.applicant
  }
  if (typeof o.respondent === 'string') {
    r.applicant = o.respondent
  }
  c.setFieldsValue(r)
}

// 初始化员工列表
async function initPersonList (setPersons: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonList())
  if (e === null && d instanceof Array) {
    setPersons(d)
  }
}

interface Props {
  params: {[k: string]: any}
  setParams: (v: {[k: string]: any}) => void
}

function Main ({params, setParams}: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [types, setTypes] = useState<DictionaryItem[]>([])
  const [persons, setPersons] = useState<string[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('结案类型')
      .then(() => {
        setTypes(d.getList('结案类型'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initPersonList(setPersons).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initForm(params, ref)
  }, [params])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '80px' }} initialValues={{ tag: '全部' }} onFinish={d => changeSearch(d, params, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          <Col span={8}>
            <Item label='案号' name='caseno_desc'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='办案秘书' name='processer'>
              <Select placeholder='请选择' showSearch allowClear>
                {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='受理秘书' name='accepter'>
              <Select placeholder='请选择' showSearch allowClear>
                {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='收案时间' name='acceptDate'>
              <DatePicker.RangePicker className={style.full} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='立案时间' name='docketDate'>
              <DatePicker.RangePicker className={style.full} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='结案时间' name='closureDate'>
              <DatePicker.RangePicker className={style.full} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='结案方式' name='closure_type'>
              <Select placeholder='请选择'>
                {
                  types.map((li, i) => {
                    return <Option key={i} value={li.value}>{li.title}</Option>
                  })
                }
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='归档时间' name='fileDate'>
              <DatePicker.RangePicker className={style.full} />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='申请人' name='applicant'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='被申请人' name='respondent'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={16} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main
